﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Person;
using BrokerBase.Lib.Policy;
using BrokerBase.Lib.Core;
using Broker.View.Comm;
using BrokerBase.Lib.Company;
using BrokerBase.Lib.Query;
using BrokerBase.Lib.Product;

namespace Broker.View.PolicyView
{


    /// <summary>
    /// PolicyListPage.xaml 的交互逻辑
    /// </summary>
    public partial class SchemeListPage 
    {
        private const int PAGE_SIZE = 12;

        private PagingQuery pageingQuery;

        private string hqlBase = "from Scheme as s ";


        private IPerson person;

        public SchemeListPage()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(SchemeListPage_Loaded);
        }

        public SchemeListPage(IPerson person):this()
        {
            this.person = person;
        }

        void SchemeListPage_Loaded(object sender, RoutedEventArgs e)
        {

            LoadCompanies();

            dpList.PageSize = PAGE_SIZE;

            if (person != null)
            {
                SetPerson();
            }
        }

        private void SetPerson()
        {
            txtInsurantName.Text = person.Name;
            txtInsurantName.IsReadOnly = true;
        }

        private void btnFast_Click(object sender, RoutedEventArgs e)
        {
            IPerson holder = new Person();

            holder.Birthday = new DateTime(1982,6,1);

            IPerson insurant = new Person();
            insurant.Birthday = new DateTime(1982, 6, 1);

            IScheme scheme = new Scheme();
            scheme.Insurant = insurant;
            scheme.Holder = holder;


            Scheme2Form frm = new Scheme2Form(scheme,SchemeType.Fast);

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = LibGlobal.MainWin;

            frm.ShowDialog();
        }



        private void dpList_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {
            if (pageingQuery != null)
            {
                //pageingQuery.FirstResult = e.NewPageIndex * PAGE_SIZE;
                Query();
            }
        }

        private void LoadCompanies()
        {
            BaseService<Company> svr = new BaseService<Company>(LibGlobal.HbmSessionFactory.GetCurrentSession());

            IList<ICompany> ls = svr.GetListByHQL("from Company Order by Name").Cast<ICompany>().ToList<ICompany>();

            ICompany cmp = new Company();
            cmp.Name = "[全部]";
            cmp.Id = 0;

            ls.Insert(0, cmp);

            cmbCompany.ItemsSource = ls;

            ICompany cp = null;
            if (LibGlobal.GetCurrentCompany != null)
                cp = LibGlobal.GetCurrentCompany();

            cmbCompany.SelectedItem = cp;

            if (cp != null && cp.Id != 0)
            {
                cmbCompany.IsEnabled = false;
            }

        }

        private IScheme GetFastScheme()
        {
            IPerson holder = new Person();

            holder.Birthday = new DateTime(1982, 6, 1);
            holder.Sex = SexType.Male;

            IPerson insurant = new Person();
            insurant.Birthday = new DateTime(1982, 6, 1);
            insurant.Sex = SexType.Male;

            IScheme scheme = new Scheme();
            scheme.Insurant = insurant;
            scheme.Holder = holder;

            return scheme;
        }

        protected void Query()
        {
            try
            {
                busyRoot.IsBusy = true;
                busyRoot.BusyContent = "正在加载数据...";

                BaseService<Scheme> svr = new BaseService<Scheme>(LibGlobal.HbmSessionFactory.GetCurrentSession());
                long total = 0;
                IList<Scheme> ls = svr.GetListByHQLWithPaging(pageingQuery.HQL, pageingQuery.TotalHQL, pageingQuery.FirstResult, PAGE_SIZE, out total);

                dpList.ItemCount = (int)total;
                gvScheme.ItemsSource = ls;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                busyRoot.IsBusy = false;
            }
        }

        private void btnAddScheme_Click(object sender, RoutedEventArgs e)
        {
            IScheme scheme = new Scheme();

            scheme.BizDate = DateTime.Now;
            scheme.CreateDate = DateTime.Now;
            scheme.Insurant = this.person;

            IPolicyLight pl = new PolicyLight(scheme, new Policy(scheme, ProductType.Basic));//默认添加一个主险
            scheme.PolicyLights.Add(pl);

            Scheme2Form frm = new Scheme2Form(scheme, SchemeType.Normal,this.person);

            frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            frm.Owner = LibGlobal.MainWin;

            frm.SaveCallBack = (IScheme s) =>
                {
                    BuildQuery();
                    Query();
                };

            frm.Show();
        }

        private void btnEditScheme_Click(object sender, RoutedEventArgs e)
        {
            View();
        }

        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            BuildQuery();
            Query();
        }

        private void btnDelScheme_Click(object sender, RoutedEventArgs e)
        {
            this.Cursor = Cursors.Wait;
            try
            {
                IScheme scheme = gvScheme.SelectedItem as IScheme;

                if (scheme != null)
                {
                    if (MessageBox.Show("是否要删除保险方案", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        IBaseService<Scheme> svr = new BaseService<Scheme>(LibGlobal.HbmSessionFactory.GetCurrentSession());

                        svr.Delete(scheme as Scheme);

                        Query();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }

        }

        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            BuildQuery();
            Query();
        }

        private void View()
        {
            IScheme scheme = gvScheme.SelectedItem as IScheme;

            if (scheme != null)
            {
                Scheme2Form frm = new Scheme2Form(scheme,SchemeType.Normal);

                frm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                frm.Owner = LibGlobal.MainWin;

                frm.SaveCallBack = (IScheme s) =>
                {
                    BuildQuery();
                    Query();
                };
                frm.Show();
            }
        }

        private void BuildQuery()
        {
            pageingQuery = new PagingQuery();

            string where = "where 1=1";

            if (person != null)
            {
                int personId = (person as Person).Id;
                where += string.Format(" and (s.Insurant.Id ={0} or s.Holder.Id={1})", personId,personId);
            }else if(!string.IsNullOrEmpty(txtInsurantName.Text))
            {
                string name = txtInsurantName.Text.Trim();
                where += string.Format(" and (s.Insurant.Name Like '%{0}%' or s.Holder.Name Like '%{1}%')", name,name);
            }

            if (dateStart.SelectedDate!=null)
            {
                where += string.Format(" and s.BizDate >='{0}'", dateStart.SelectedDate.Value.ToString("yyyy-MM-dd"));
            }

            if (dateEnd.SelectedDate != null)
            {
                where += string.Format(" and s.BizDate <='{0}'", dateEnd.SelectedDate.Value.ToString("yyyy-MM-dd"));
            }

            if (cmbCompany.SelectedItem != null && ((ICompany)cmbCompany.SelectedItem).Id != 0)
            {
                ICompany c = cmbCompany.SelectedItem as ICompany;
                where += string.Format(" and exists (from Policy as p where p.Owner.Id = s.Id and p.Product.Company.Id={0})",c.Id);
            }

            if (!string.IsNullOrEmpty(txtProductName.Text))
            {
                where += string.Format(" and exists (from Policy as p where p.Owner.Id = s.Id and p.Product.Name Like '%{0}%')",txtProductName.Text.Trim());
            }

            if (rbCheck.IsChecked==true)
            {
                where += string.Format(" and s.CheckTime is not null");
            }

            if (rbUnCheck.IsChecked == true)
            {
                where += string.Format(" and s.CheckTime is null");
            }

            pageingQuery.HQL = hqlBase + where + " order by s.CreateDate desc";
            pageingQuery.TotalHQL = "select count(*) " + hqlBase + where;
        }

        private void gvScheme_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            View();
        }


    }
}
